package algebra.rewriting.transform;

import algebra.op.AlgebraicOP;
import algebra.op.JoinOP;
import algebra.op.SelectionOP;
import algebra.rewriting.RewriteRule;

public class CommutativeSelection extends RewriteRule {

	private final AlgebraicOP op;

	public CommutativeSelection(AlgebraicOP op) {
		this.op = op;
	}

	@Override
	public AlgebraicOP rewrite() {
		SelectionOP ip = (SelectionOP) op;
		SelectionOP sp = ip.getSubquery().asSelectionOP();
		AlgebraicOP inner = sp.getSubquery();
		return new SelectionOP(new SelectionOP(inner,
				ip.getSelectionCondition(), ip.getPlanEvalKB()),
				sp.getSelectionCondition(), sp.getPlanEvalKB());
	}

	@Override
	public boolean applicable() {
		if (this.op instanceof SelectionOP) {
			if (this.op.asSelectionOP().getSubquery() instanceof SelectionOP) {
				return true;
			}
		}
		return false;
	}

}
